package com.sxit.tdf.server.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxit.tdf.server.entity.File;
import com.sxit.tdf.server.entity.FileBucket;
import com.sxit.tdf.server.entity.FilePath;
import com.sxit.tdf.server.entity.User;
import com.sxit.tdf.server.entity.bo.*;
import com.sxit.tdf.server.entity.vo.InsertFileFolderVo;
import com.sxit.tdf.server.entity.vo.InsertUpLoadFileVo;
import com.sxit.tdf.server.entity.vo.SiftFileInfoVo;
import com.sxit.tdf.server.entity.vo.UpLoadPrivateFileVo;
import com.sxit.tdf.server.exception.TdfException;
import com.sxit.tdf.server.mapper.FileMapper;
import com.sxit.tdf.server.service.IFileBucketService;
import com.sxit.tdf.server.service.IFilePathService;
import com.sxit.tdf.server.service.IFileService;
import com.sxit.tdf.server.service.IUserService;
import com.sxit.tdf.server.util.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 服务实现类
 *
 * @author 橙子高
 * @since 2022-02-23
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService {

  @Autowired private IFileBucketService bucketService;
  @Autowired private IFilePathService filePathService;
  @Autowired private IUserService userService;

  @Value("${my_oss.file_path}")
  private String myFilePath;

  @Override
  @Transactional
  public Boolean uploadFile(InsertUpLoadFileVo insertUpLoadFileVo) throws IOException {
    System.out.println(insertUpLoadFileVo);
    Boolean isCanInsert =
        baseMapper.isCanInsert(
            insertUpLoadFileVo.getFileName(),
            insertUpLoadFileVo.getFile().getOriginalFilename(),
            insertUpLoadFileVo.getFilePathId());

    if (isCanInsert) {
      throw new TdfException("文件夹中以存在该文件");
    }
    // 获取文件流
    MultipartFile multipartFile = insertUpLoadFileVo.getFile();
    byte[] bytes = multipartFile.getBytes();
    // 获取扩展名
    String filename = multipartFile.getOriginalFilename();
    String ext = filename.substring(filename.lastIndexOf(".") + 1);

    // 获取筒信息
    FileBucket bucket = bucketService.getById(insertUpLoadFileVo.getFileBucketId());
    // 获取文件夹信息
    FilePath filePath = filePathService.getById(insertUpLoadFileVo.getFilePathId());

    String uuidFileName = UUID.fastUUID() + "." + ext;

    File file = new File();
    file.setFileName(insertUpLoadFileVo.getFileName());
    file.setFileSuffix(ext);
    file.setFilePathId(insertUpLoadFileVo.getFilePathId());
    file.setFileBucketId(insertUpLoadFileVo.getFileBucketId());
    file.setIsDelete(0);
    file.setCreateTime(LocalDateTime.now());
    file.setFileDownload(0);
    file.setFileOwnerId(insertUpLoadFileVo.getFileOwnerId());
    file.setFileDescribe(insertUpLoadFileVo.getFileDescribe());
    file.setFileOssPath(
        "https://"
            + bucket.getBucketCode()
            + ".oss-cn-beijing.aliyuncs.com/"
            + filePath.getPathCode()
            + uuidFileName);
    file.setFileRealName(filename);
    file.setFileType("1");
    int insert = baseMapper.insert(file);

    if (insert == 1) {
      new OSSUtil().uploadFile(bucket.getBucketCode(), filePath.getPathCode(), uuidFileName, bytes);
      return true;
    }

    return false;
  }

  @Override
  public Boolean deleteById(String id) {
    File file = baseMapper.selectById(id);
    //    FileBucket bucket = bucketService.getById(file.getFileBucketId());
    //    FilePath filePath = filePathService.getById(file.getFilePathId());

    //    OSSUtil ossUtil = new OSSUtil();
    //    ossUtil.deleteFile(bucket.getBucketCode(), filePath.getPathCode(), file.getFileName());

    int i = baseMapper.deleteById(id);
    return i != 0;
  }

  @Override
  public List<String> getSuffix() {
    return baseMapper.getSuffix();
  }

  @Override
  public List<FileInfoBo> getAllFileInfo(
      String pathCode,
      String bucketName,
      String fileSuffix,
      Long pageSize,
      String fileOwnUserName,
      Integer current,
      String fileName) {
    Page<FileInfoBo> page = new Page<FileInfoBo>(current, pageSize);
    return baseMapper.getAllFileInfo(
        page, pathCode, bucketName, fileSuffix, fileOwnUserName, fileName);
  }

  @Override
  public List<SimpleFileStoreInfo> getStoreFileInfo(List<Integer> ids) {

    return baseMapper.getStoreFileInfo(ids);
  }

  @Override
  public StoreFileInfoBo getStoreFileById(String id) {
    return baseMapper.getStoreFileById(id);
  }

  @Override
  public void addFileDownload(String id) {

    baseMapper.addFileDownload(id);
  }

  @Override
  public ComplexFileMessageBo getMessage() {

    ComplexFileMessageBo messageBo = new ComplexFileMessageBo();

    Long fileNumber = baseMapper.getFileCount();
    Long onlineFileNumber = baseMapper.selectCountByType(1);
    Long offLineFileNumber = baseMapper.selectCountByType(2);
    Long fileDownLoadNumber = baseMapper.getFileDownLoadNumber();
    Long fileUploadNumber = baseMapper.getfileUploadNumber();
    List<fileIncrement> fileIncrementList = baseMapper.getFileIncrementList();
    List<fileTypeNumber> fileTypeNumberList = baseMapper.getFileTypeNumberList();
    List<fileStoreNumber> fileStoreNumberList = baseMapper.getFileStoreNumberList();
    ArrayList<String> message;
    try {
      message = new OSSUtil().getMessage();

    } catch (Exception e) {
      throw new TdfException("OSS请求发生错误");
    }

    messageBo.setFileNumber(fileNumber);
    messageBo.setOnlineFileNumber(onlineFileNumber);
    messageBo.setOfflineFileNumber(offLineFileNumber);
    messageBo.setFileDownloadNumber(fileDownLoadNumber);
    messageBo.setFileUploadNumber(fileUploadNumber);
    messageBo.setFileIncrementList(fileIncrementList);
    messageBo.setFileTypeNumberList(fileTypeNumberList);
    messageBo.setFileStoreNumberList(fileStoreNumberList);
    messageBo.setFileStreamValues(message);
    return messageBo;
  }

  @Override
  public IPage<ComplexFileDataBo> getComplexFileInfo(SiftFileInfoVo siftFileInfoVo) {

    HashMap hashMap = JSONUtil.parse(siftFileInfoVo).toBean(HashMap.class);

    Page<ComplexFileDataBo> page =
        new Page<ComplexFileDataBo>(siftFileInfoVo.getCurrent(), siftFileInfoVo.getPageSize());
    return baseMapper.getComplexFileInfo(page, hashMap);
  }

  @Override
  public List<String> getALLSuffix() {
    return baseMapper.getALLSuffix();
  }

  @Override
  public List<PrivateFileListBo> getPrivateFileList(String userId) {
    return baseMapper.getPrivateFileList(userId);
  }

  @Override
  public boolean UpLoadPrivateFileVo(
      String userId, UpLoadPrivateFileVo upLoadPrivateFileVo, MultipartFile multipartFile)
      throws IOException {

    // 获取文件流

    byte[] bytes = multipartFile.getBytes();
    // 获取扩展名
    String filename = multipartFile.getOriginalFilename();
    String ext = filename.substring(filename.lastIndexOf(".") + 1);

    // 判断文件夹是否存在
    FilePath fileByPathCode = filePathService.findFileByPathCode(userId + "/");
    Integer pathId;
    if (fileByPathCode == null) {

      User byId = userService.getById(userId);

      InsertFileFolderVo insertFileFolderVo = new InsertFileFolderVo();
      insertFileFolderVo.setPathName(byId.getName() + byId.getNum());
      insertFileFolderVo.setParent(0);
      insertFileFolderVo.setPathCode(userId + "/");
      insertFileFolderVo.setBucketId(10);

      filePathService.createFileFolder(insertFileFolderVo);
      pathId = filePathService.findFileByPathCode(userId + "/").getId();

    } else {
      pathId = fileByPathCode.getId();
    }

    String uuidFileName = UUID.fastUUID() + "." + ext;

    File file = new File();
    file.setFileName(upLoadPrivateFileVo.getFileName());
    file.setFileSuffix(ext);
    file.setFilePathId(pathId);
    file.setFileBucketId(10);
    file.setIsDelete(0);
    file.setCreateTime(LocalDateTime.now());
    file.setFileDownload(0);
    file.setFileOwnerId(userId);
    file.setFileDescribe(upLoadPrivateFileVo.getFileDescribe());
    file.setFileOssPath(
        "https://"
            + "gerenwenjian148"
            + ".oss-cn-beijing.aliyuncs.com/"
            + userId
            + "/"
            + uuidFileName);
    file.setFileRealName(filename);
    file.setFileType("1");
    int insert = baseMapper.insert(file);

    if (insert == 1) {
      new OSSUtil().uploadFile("gerenwenjian148", userId + "/", uuidFileName, bytes);
      return true;
    }

    return false;
  }

  @Override
  public HashMap<String, Object> getPrivateFileInfoMsg(String userId) {

    QueryWrapper<File> fileQueryWrapper = new QueryWrapper<>();
    fileQueryWrapper.eq("file_owner_id", userId).eq("is_delete", 0);

    HashMap<String, Object> map = new HashMap<>();
    // 获取总共的文件数量
    Long count = baseMapper.selectCount(fileQueryWrapper);
    map.put("all", count);

    // 获取上传文件的数量
    QueryWrapper<File> fileQueryWrapper1 = new QueryWrapper<>();
    fileQueryWrapper1.eq("file_owner_id", userId).eq("is_delete", 0).eq("file_type", 1);
    Long aLong = baseMapper.selectCount(fileQueryWrapper1);
    map.put("online", aLong);

    Long number = baseMapper.selectCountApprover(userId);
    map.put("approver", number);

    Long c = baseMapper.getCountRefult(userId);
    map.put("refult",c);

    return map;
  }
}
